<?php
declare (strict_types=1);

namespace app\common\model;

class Course extends Base
{
    public function cate()
    {
        return $this->hasOne(CollegeCate::class, 'id', 'cate')->field('id,title');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function getTypeNameAttr($value, $data)
    {
        return courseType($data['type']);
    }

    public function getIsFreeNameTextAttr($value, $data)
    {
        return courseIsFree($data['is_free']);
    }

    public static function _save($param, $admin)
    {
        try {
            if ($param['is_free'] == 1) {
                $param['price'] = 0;
                $param['uid'] = 0;
                $param['rebate_amount'] = 0;
            } else {
                if ($param['price'] <= 0) {
                    throw new \Exception('价格设置有误');
                }
                $uid = User::where(['code' => $param['user_code']])->value('id');
                if (!$uid) {
                    throw new \Exception('会员编号不存在');
                }
                $param['uid'] = $uid;
            }
            if ($param['type'] == 'image_text') {
                $param['link'] = '';
            } else {
                $param['link'] = $param[$param['type'].'_link'];
            }
            if ($param['id']) {
                parent::update($param, ['id' => $param['id']]);
            } else {
                parent::create($param);
            }

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
